package com.freewater.javabase.demo.network.cookie;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

public class CookieStoreDemo {
    public static void main(String[] args) throws IOException {
        CookieManager cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER); // 只接受第一方cookie，不接受第三方cookie
        CookieHandler.setDefault(cookieManager); // 设置为默认的CookieHandler
        URL url = new URL("https://www.baidu.com");
        final String userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36";
        final URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("User-Agent", userAgent); // 需要设置User-Agent头，否则百度不会返回cookies
        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedInputStream is = new BufferedInputStream(urlConnection.getInputStream());
             InputStreamReader reader = new InputStreamReader(is)) {
            char[] buffer = new char[1024];
            int read;
            while ((read = reader.read(buffer)) != -1) {
                contentBuilder.append(buffer, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("-----------------content--------------------");
        System.out.println(contentBuilder.substring(0, 200));
        System.out.println("-----------------cookies--------------------");
        final CookieStore cookieStore = cookieManager.getCookieStore();
        cookieStore.getCookies().forEach(cookie -> System.out.println(cookie));
    }
}
